﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using entity;
using System.Data;

namespace DAL
{
    /// <summary>
    ///  千股千评
    /// </summary>
    public class QgqpDAL
    {
        public TopicsStock GetQgqp(TopicsStock c)
        {
            string stock = c.Stock;
            if (!stock.StartsWith("6"))
            {
                stock = "1" + stock;
            }
            string sql = "select total_score,tech_desc,industry_desc from dbo.vw_score  where stock_id='" + stock + "'";
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, System.Data.CommandType.Text, sql, null);
            if (tb.Rows.Count > 0)
            {
                var row = tb.Rows[0];
                //c.QGQP = Tools.GetString(row["tech_desc"]);
                c.TJPF = Tools.GetDecimal(row["total_score"]);
            }
            return c;
        }

        public DataRow GetQgqp(string stockId)
        {
            if (!stockId.StartsWith("6"))
            {
                stockId = "1" + stockId;
            }
            string sql = "select total_score,tech_desc from dbo.vw_score  where stock_id=@stock";
            Tools tool = new Tools();
            tool.AddSqlParameter("stock", SqlDbType.VarChar, stockId);
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, tool.GetSqlParameters());
            if (tb.Rows.Count > 0)
            {
                return tb.Rows[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        ///  根据板块编号--排序按照得分的逆序排列
        /// </summary>
        /// <param name="bkid">板块编号</param>
        /// <returns>股票代码</returns>
        public List<string> GetStocksByPf(string bkid)
        {
            bkid = "BK" + bkid.Substring(2);
            string sql = "select * from vw_score where block_id=@bkid ORDER BY TOTAL_SCORE DESC";
            Tools tool = new Tools();
            tool.AddSqlParameter("bkid", SqlDbType.VarChar, bkid);
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, tool.GetSqlParameters());
            List<string> lst = new List<string>();
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                DataRow row = tb.Rows[i];
                string stock = Tools.GetString(row["stock_id"]);
                if (!string.IsNullOrEmpty(stock))
                {
                    if (stock.Length == 7)
                    {
                        stock = stock.Substring(1);
                    }
                    lst.Add(stock);
                }
            }
            return lst;
        }

        /// <summary>
        /// 得到全部的千股前评
        /// </summary>
        /// <returns></returns>
        public List<StockScore> GetAllStockScore()
        {
            string sql = "select stock_id,total_score,total_desc from vw_score";
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, System.Data.CommandType.Text, sql, null);
            List<StockScore> lst = new List<StockScore>();
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                DataRow row = tb.Rows[i];
                StockScore c = new StockScore();
                c = new StockScore();
                c.StockId = Tools.GetString(row["stock_id"]);
                if (c.StockId.Length == 7)
                {
                    c.StockId = c.StockId.Substring(1);
                }
                c.TotalScore = Tools.GetDecimal(row["total_score"]);
                c.TotalDesc = Tools.GetString(row["total_desc"]);
                lst.Add(c);
            }
            return lst;

        }

        public DataTable Get大盘操盘摘要()
        {
            string sql = "select top 1 * from VW_WEB_MARKET_DES order by date desc";
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, System.Data.CommandType.Text,sql, null);
            return tb;
        }

        public StockScore GetStockScore(string stockId)
        {
            if (!stockId.StartsWith("6"))
            {
                stockId = "1" + stockId;
            }
            string sql = "select * from dbo.vw_score  where stock_id=@stockId";
            Tools tool = new Tools();
            tool.AddSqlParameter("stockId", System.Data.SqlDbType.VarChar, stockId);
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, System.Data.CommandType.Text, sql, tool.GetSqlParameters());
            StockScore c = null;
            if (tb.Rows.Count > 0)
            {
                DataRow row = tb.Rows[0];
                c = new StockScore();
                c.StockId = Tools.GetString(row["stock_id"]);
                c.BKId = Tools.GetString(row["block_id"]);
                c.BasicScore = Tools.GetDecimal(row["basic_score"]);
                c.MsgScore = Tools.GetDecimal(row["msg_score"]);
                c.IndustryScore = Tools.GetDecimal(row["industry_score"]);
                c.MajorScore = Tools.GetDecimal(row["major_score"]);
                c.TechScore = Tools.GetDecimal(row["tech_score"]);
                c.TotalScore = Tools.GetDecimal(row["total_score"]);
                c.TechDetail = Tools.GetString(row["tech_detail"]);
                c.Analysis = Tools.GetString(row["analysis"]);
                c.BasicDesc = Tools.GetString(row["basic_desc"]);
                c.MsgDesc = Tools.GetString(row["msg_desc"]);
                c.IndustryDesc = Tools.GetString(row["industry_desc"]);
                c.MajorDesc = Tools.GetString(row["major_desc"]);
                c.TechDetail = Tools.GetString(row["tech_desc"]);
                c.TotalDesc = Tools.GetString(row["total_desc"]);
            }
            return c;
        }

        public List<IndustryStatus> GetAllIndustryStatus()
        {
            string sql = "select * from vw_block_brief order by date desc";
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            List<IndustryStatus> lst = new List<IndustryStatus>();
            foreach (DataRow row in tb.Rows)
            {
                IndustryStatus c = new IndustryStatus();
                c.Author = "";
                c.BKID = Tools.GetString(row["block_id"]);
                c.Date = DateTime.Now;
                c.Future = Tools.GetString(row["future"]);
                c.Id = 0;
                c.Now = Tools.GetString(row["now"]);
                lst.Add(c);
            }
            return lst;
        }

        public List<InvestmentHighlights> GetAllInvestmentHighlights()
        {
            string sql = "select * from vw_block_invest order by date desc";
            var tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            List<InvestmentHighlights> lst = new List<InvestmentHighlights>();
            foreach (DataRow row in tb.Rows)
            {
                InvestmentHighlights c = new InvestmentHighlights();
                c.BKID = Tools.GetString(row["block_id"]);
                c.Date = Tools.GetDateTime(row["date"]);
                c.Id = Tools.GetLong(row["id"]);
                c.Point = Tools.GetString(row["point"]);
                c.Reason = Tools.GetString(row["reason"]);
                lst.Add(c);
            }
            return lst;
        }

        /// <summary>
        /// 得到所有的道破天机数据
        /// </summary>
        /// <returns></returns>
        public List<LaybareSecret> GetDPTJ()
        {
            string sql = "select * from vw_website_reveal_secret";
            DataTable tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            List<LaybareSecret> lst = new List<LaybareSecret>();
            foreach (DataRow row in tb.Rows)
            {
                LaybareSecret c = new LaybareSecret();
                c.Change_num = Tools.GetLong(row["Change_num"]);
                c.Change_rate = Tools.GetDecimal(row["Change_rate"]);
                c.Date = Tools.GetDateTime(row["Date"]);
                c.Flow_rate = Tools.GetDecimal(row["Flow_rate"]);
                c.Fund_num = Tools.GetInt(row["Fund_num"]);
                c.Fundchange_num = Tools.GetInt(row["Fundchange_num"]);
                c.Hold_Marketvalue = Tools.GetDecimal(row["Hold_Marketvalue"]);
                c.Hold_num = Tools.GetDecimal(row["Hold_num"]);
                c.Lasthold_num = Tools.GetLong(row["Lasthold_num"]);
                c.StockId = Tools.GetString(row["stock_id"]);
                c.Total_rate = Tools.GetDecimal(row["Total_rate"]);
                lst.Add(c);
            }
            return lst;
        }

        /// <summary>
        /// 得到天气预报
        /// </summary>
        /// <returns></returns>
        public DataRow GetStockWeather()
        {
            //DataTable tb2 = new DataTable();
            //tb2.Columns.Add("date");
            //tb2.Columns.Add("weather");
            //tb2.Columns.Add("content");
            //tb2.Columns.Add("posi");
            //tb2.Columns.Add("short_strategy");
            //tb2.Columns.Add("long_strategy");
            //var newRow = tb2.NewRow();
            //newRow["date"] = "20130110";
            //newRow["weather"] = "8";
            //newRow["content"] = "升势受阻，获利回吐";
            //newRow["posi"] = "100.000";
            //newRow["short_strategy"] = "积极做多";
            //newRow["long_strategy"] = "满仓持股";
            //return newRow;
            string sql = "select top 1 cast(date as bigint) as date,weather,[content],posi,short_strategy,long_strategy from weather_forecast order by date desc";
            DataTable tb = SqlHelper.ExecuteGetTable(DBManager.qgqp2, CommandType.Text, sql, null);
            if (tb.Rows.Count > 0)
            {
                return tb.Rows[0];
            }
            else
            {
                return null;
            }
        }

        public DataTable Get操盘摘要()
        {
            string sql = "sp_report_industry_status";
            DataTable tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            return tb;
        }

        public StockTrend GetStockTrend(string code)
        {
            if (!code.StartsWith("6"))
            {
                code = "1" + code;
            }
            Tools tool = new Tools();
            tool.AddSqlParameter("stock", SqlDbType.VarChar, code);
            string sql = "SELECT top 1 * FROM dbo.tech_score where stock_id=@stock";
            var tb=SqlHelper.ExecuteGetTable(DBManager.qgqp2, CommandType.Text,sql ,tool.GetSqlParameters());
            if (tb.Rows.Count > 0)
            {
                DataRow row = tb.Rows[0];
                StockTrend st = new StockTrend();
                st.K线形态 =ReplaceKey( Convert.ToString( row["k_line"]));
              
                st.成交量能 =ReplaceKey( Convert.ToString( row["match_energy"]));
                st.趋势状态 =ReplaceKey( Convert.ToString(row["trend_state"]));
                st.相对强弱 =ReplaceKey( Convert.ToString(row["stong_weak"]));
                st.资金流向 =ReplaceKey( Convert.ToString(row["capital_flow"]));
                return st;
            }
            else
            {
                return new StockTrend();
            }
        }

        string ReplaceKey(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return str.Replace("○", "").Replace("●", "");
            }
            else
            {
                return "";
            }
        }

        string getValue(string str)
        {
             str= str.Substring(str.IndexOf(">")+1);
             str=str.Substring(0,str.IndexOf("<"));
             return str;
        }
        public string  Get行业新闻(string bkid)
        {
            if(bkid.StartsWith("00"))
            {
                bkid= "BK"+bkid.Substring(2);
            }
            string sql="SELECT TOP 1 Title FROM vw_website_industry_news where BLOCK_ID=@bkid  ORDER BY date desc";
            Tools tool=new Tools();
            tool.AddSqlParameter("bkid", SqlDbType.VarChar,bkid);
            return Tools.GetString( SqlHelper.ExecuteScalar(DBManager.qgqp, CommandType.Text,sql,tool.GetSqlParameters()));

        }

        StockTrend GetStockTrend2(string str)
        {
            StockTrend c = new StockTrend();
            string[] s = new string[] { "<br>", "\r\n" };
            string[] strs = str.Split(s, StringSplitOptions.RemoveEmptyEntries);
            var lst = strs.Where(x => x.Trim() != "").ToList();
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i].Contains("趋势状态"))
                {
                    c.趋势状态xx = GetStar(lst[++i]);
                    i++;
                    while (!lst[i].Contains("K线形态"))
                    {
                        c.趋势状态 += getValue(lst[i]) + ",";
                        i++;
                    }
                    if (!string.IsNullOrEmpty(c.趋势状态))
                    {
                        c.趋势状态 = c.趋势状态.Substring(0, c.趋势状态.Length - 1);
                    }
                    i--;
                }
                else if (lst[i].Contains("K线形态"))
                {
                    c.K线形态xx = GetStar(lst[++i]);
                    i++;
                    while (!lst[i].Contains("成交量能"))
                    {
                        c.K线形态 += getValue(lst[i]) + ",";
                        i++;
                    }
                    if (!string.IsNullOrEmpty(c.K线形态))
                    {
                        c.K线形态 = c.K线形态.Substring(0, c.K线形态.Length - 1);                 
                    }
                    i--;
                }
                else if (lst[i].Contains("成交量能"))
                {
                    c.成交量能xx = GetStar(lst[++i]);
                    i++;
                    while (!lst[i].Contains("相对强弱"))
                    {
                        c.成交量能 += getValue(lst[i]) + ",";
                        i++;
                    }
                    if (!string.IsNullOrEmpty(c.成交量能))
                    {
                        c.成交量能 = c.成交量能.Substring(0, c.成交量能.Length - 1);
                    }
                    i--;
                }
                else if (lst[i].Contains("相对强弱"))
                {
                    c.相对强弱xx = GetStar(lst[++i]);
                    i++;
                    while (!lst[i].Contains("资金流向"))
                    {
                        c.相对强弱 += getValue(lst[i]) + ",";
                        i++;
                    }
                    if (!string.IsNullOrEmpty(c.相对强弱))
                    {
                        c.相对强弱 = c.相对强弱.Substring(0, c.相对强弱.Length - 1);
                    }
                    i--;
                }
                else if (lst[i].Contains("资金流向"))
                {
                    c.资金流向xx = GetStar(lst[++i]);
                    i++;
                    while (!lst[i].Contains("综合得分"))
                    {
                        c.资金流向 += getValue(lst[i]) + ",";
                        i++;
                    }
                    if (!string.IsNullOrEmpty(c.资金流向))
                    {
                        c.资金流向 = c.资金流向.Substring(0, c.资金流向.Length - 1);
                    }
                    i--;
                }
            }
            return c;
        }

        int GetStar(string str)
        {
            int count = 0;
            foreach (var c in str)
            {
                if (c == '●')
                {
                    count++;
                }
            }
            return count;
        }

        public List<BKTrend> GetTrend()
        {
            string sql = "select * from vw_industry_tech_score";
            DataTable tb= SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            List<BKTrend> lst = new List<BKTrend>();
            foreach (DataRow row in tb.Rows)
            {
                BKTrend t = new BKTrend();
                t.block_id = Tools.GetString(row["block_id"]);
                t.block_score = Tools.GetDecimal(row["block_score"]);
                t.capital_flow = Tools.GetString(row["capital_flow"]);
                t.date = Tools.GetString(row["date"]);
                t.match_energy = Tools.GetString(row["match_energy"]);
                t.strong_weak = Tools.GetString(row["strong_weak"]);
                t.trend_state = Tools.GetString(row["trend_state"]);
                lst.Add(t);
            }
            return lst;
        }

        public List<BKSJ> Get板块数据()
        {
            List<BKSJ> lst = new List<BKSJ>();
            string sql = "select * from vw_web_block_finance_index";
            DataTable tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            foreach (DataRow row in tb.Rows)
            {
                BKSJ c = new BKSJ();
                c.BKID = Tools.GetString(row["BLOCK_ID"]);
                c.BKID = "00" + c.BKID.Substring(2);
                c.BKName = Tools.GetString(row["BLOCK_NAME"]);
                c.EndDate = Tools.GetDateTime(row["EndDate"]);
                c.Profit = Tools.GetDecimal(row["Profit"]);
                c.PerStockProfit = Tools.GetDecimal(row["PerStockProfit"]);
                c.Asset = Tools.GetDecimal(row["Asset"]);
                c.AssetProfit = Tools.GetDecimal(row["AssetProfit"]);
                lst.Add(c);
            }
            return lst;
        }

        public List<entity.CompanyOverview> Get公司概况()
        {
            string sql = "select * from vw_website_stock_info";
            DataTable tb = SqlHelper.ExecuteGetTable(DBManager.qgqp, CommandType.Text, sql, null);
            List<entity.CompanyOverview> lst = new List<CompanyOverview>();
            foreach (DataRow row in tb.Rows)
            {
                entity.CompanyOverview c = new CompanyOverview();
                string dq = Tools.GetString(row["REGION_ID"]);
                if (!string.IsNullOrEmpty(dq))
                {
                    dq=dq.Replace("板块", "");
                }
                c.dq = dq;
                c.jlrzzl = Tools.GetDecimal(row["net_profit_growth"]);
                c.jzcsyl = Tools.GetDecimal(row["ROE"]);
                c.ltag = Tools.GetDecimal(row["flow_share"]);
                c.mggjj = Tools.GetDecimal(row["accumulation_fund"]);
                c.mgjzc = Tools.GetDecimal(row["net_asset"]);
                c.mgsy = Tools.GetDecimal(row["EPS"]);
                c.mgwfplr = Tools.GetDecimal(row["unappropriated_profit"]);
                c.mgxjl = Tools.GetDecimal(row["cash_flow"]);
                string strListDate = Tools.GetString(row["list_date"]);
                DateTime? listDate = null;
                if (!string.IsNullOrEmpty(strListDate))
                {
                    strListDate = strListDate.Substring(0, 4)+"-" + strListDate.Substring(4, 2)+"-" + strListDate.Substring(6, 2);
                    c.sssj = DateTime.Parse(strListDate);
                }
                c.StockId = Tools.GetString(row["STOCK_ID"]);
                c.zgb = Tools.GetDecimal(row["total_share"]);
                c.zysrzzl = Tools.GetDecimal(row["business_income"]);
                lst.Add(c);
            }
            return lst;
        }
    }
}